from django.db import models

# Create your models here.
import datetime
from django.utils.safestring import mark_safe
from django.db import models
from django.core.exceptions import ValidationError
from django.utils import timezone
from base import models as baseModels
from production import models as productionModels
from datetime import datetime
from django.db import transaction
import os
from ckeditor_uploader.fields import RichTextUploadingField  # 带上传功能的富文本字段
def validate_file_size(value):
    """验证文件大小不超过5MB"""
    filesize = value.size
    if filesize > 5 * 1024 * 1024:  # 5MB
        raise ValidationError("文件大小不能超过5MB")
    allowed_extensions = [ '.img', '.jpg', '.webp']
    ext = os.path.splitext(value.name)[1].lower()
    if ext not in allowed_extensions:
        raise ValidationError('只允许上传常规文件')
    return value

# Create your models here.
class WebInfoModel(models.Model):
    '''物料入库'''
    linkman = models.CharField(max_length=50, verbose_name='联系人', default='',blank=True )# 数据库层面不允许为NULL

    phone = models.CharField(max_length=50, verbose_name='联系电话', default='',blank=True )# 数据库层面不允许为NULL
    tel = models.CharField(max_length=50, verbose_name='联系座机', default='',blank=True )  # 数据库层面不允许为NULL
    email = models.EmailField( verbose_name='邮箱', default='', null=True,blank=True )  # 数据库层面允许为NULL
    address = models.CharField(max_length=250, verbose_name='地址', default='',blank=True )  # 数据库层面不允许为NULL
    content = models.TextField(max_length=250, verbose_name='简介', default='', blank=True)  # 数据库层面不允许为NULL
    STATE_CHOICES = [
        ("1", "是"),
        ("0", "否"),
    ]
    state = models.CharField(max_length=50, verbose_name='展示', default='1', choices=STATE_CHOICES)

    # 先定义动态 upload_to 函数（关键）
    def dynamic_upload_path(instance, filename):
        """
        动态生成文件上传路径
        格式: uploads/files/report/[用户ID]/[应用标签]/[模型名称]/[文件名]
        """

        # 拼接路径（将特殊字符替换为下划线，避免路径错误）
        return f"uploads/files/website/{instance.pk}/{filename}"

    logo = models.ImageField(upload_to=dynamic_upload_path, validators=[validate_file_size],
                             verbose_name='logo',blank=True)
    create_at = models.DateTimeField(verbose_name='创建日期',default=timezone.now ) # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)
    class Meta:
        verbose_name='官网信息'
        verbose_name_plural = '官网信息'  # 自定义复数形式，与单数相同



# Create your models here.
class WebPage(models.Model):
    title = models.CharField(max_length=50, verbose_name='标题', default='',null=False, blank=False)
    content = RichTextUploadingField(verbose_name='内容')
    STATE_CHOICES = [
        ("1", "启用"),
        ("0", "停用"),
    ]
    state = models.CharField(max_length=50, verbose_name='状态', default='1', choices=STATE_CHOICES)
    create_at = models.DateTimeField(verbose_name='创建日期', default=timezone.now)  # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)
    class Meta:
        verbose_name='企业简介'
        verbose_name_plural = '企业简介'  # 自定义复数形式，与单数相同
    def __str__(self):
        return self.title

class WebMessageModel(models.Model):
    '''物料入库'''
    title = models.CharField(max_length=255, verbose_name='标题', null=False,blank=False )# 数据库层面不允许为NULL
    linkman = models.CharField(max_length=255, verbose_name='联系人', null=False, blank=False)
    phone = models.CharField(max_length=50, verbose_name='联系电话', null=False,blank=False )# 数据库层面不允许为NULL

    email = models.EmailField( verbose_name='邮箱', default='', null=True,blank=True )  # 数据库层面允许为NULL
    address = models.CharField(max_length=250, verbose_name='地址', default='',blank=True )  # 数据库层面不允许为NULL
    contents = models.CharField(max_length=250, verbose_name='内容', null=False,blank=False)


    create_at = models.DateTimeField(verbose_name='创建日期',default=timezone.now ) # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)
    class Meta:
        verbose_name='留言'
        verbose_name_plural = '留言'  # 自定义复数形式，与单数相同


class WebNews(models.Model):
    title = models.CharField(max_length=50, verbose_name='标题', default='',null=False, blank=False)
    content = RichTextUploadingField(verbose_name='内容')
    STATE_CHOICES = [
        ("1", "启用"),
        ("0", "停用"),
    ]
    state = models.CharField(max_length=50, verbose_name='首页展示', default='1', choices=STATE_CHOICES)
    enable = models.CharField(max_length=50, verbose_name='状态', default='1', choices=STATE_CHOICES)
    create_at = models.DateTimeField(verbose_name='创建日期', default=timezone.now)  # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)
    class Meta:
        verbose_name='新闻'
        verbose_name_plural = '新闻'  # 自定义复数形式，与单数相同
    def __str__(self):
        return self.title

class WebProducts(models.Model):
    title = models.CharField(max_length=50, verbose_name='产品名称', default='',null=False, blank=False)
    content = RichTextUploadingField(verbose_name='内容')
    STATE_CHOICES = [
        ("1", "是"),
        ("0", "否"),
    ]
    state = models.CharField(max_length=50, verbose_name='首页展示', default='1', choices=STATE_CHOICES)
    enable = models.CharField(max_length=50, verbose_name='展示', default='1', choices=STATE_CHOICES)
    create_at = models.DateTimeField(verbose_name='创建日期', default=timezone.now)  # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)
    # 先定义动态 upload_to 函数（关键）
    def dynamic_upload_path(instance, filename):
        """
        动态生成文件上传路径
        格式: uploads/files/report/[用户ID]/[应用标签]/[模型名称]/[文件名]
        """

        # 拼接路径（将特殊字符替换为下划线，避免路径错误）
        return f"uploads/files/website/products/{instance.pk}/{filename}"

    img = models.ImageField(upload_to=dynamic_upload_path, validators=[validate_file_size],
                             verbose_name='产品图片', blank=True)
    create_at = models.DateTimeField(verbose_name='创建日期', default=timezone.now)  # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)

    class Meta:
        verbose_name='产品'
        verbose_name_plural = '产品'  # 自定义复数形式，与单数相同
    def __str__(self):
        return self.title